package org.grow.present.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.grow.present.properties.WxProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

@Service

public class WxLoginService {
    @Autowired
    private WxProperties wxProperties;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private OkHttpClient okHttpClient;
    public final static String wxUrl = "https://api.weixin.qq.com/sns/jscode2session";

    //    return openid;
    public String login(String code) {
//        String url = wxProperties.getWxUrl() + "?" + "appid=" + wxProperties.getAccessKey() + "&" + "secret=" + wxProperties.getSecretKey()
//                + "&js_code=" + code + "&grant_type=authorization_code";
        HttpUrl.Builder urlBuilder = HttpUrl.parse(wxUrl).newBuilder();
        urlBuilder.addQueryParameter("appid", wxProperties.getAccessKey());
        urlBuilder.addQueryParameter("secret", wxProperties.getSecretKey());
        urlBuilder.addQueryParameter("js_code", code);
        urlBuilder.addQueryParameter("grant_type", "authorization_code");
        String url = urlBuilder.build().toString();
        System.out.println("build url " + url);
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(url)
                .get()
                .build();

        Call call = okHttpClient.newCall(request);
        Response response;
        try {
            response = call.execute();
            ResponseBody body = response.body();
            Map map = objectMapper.readValue(body.charStream(), Map.class);
            String openid = (String) map.get("openid");
            System.out.println(openid);
            return openid;

        } catch (IOException e) {
            System.out.println("远程调用获取openId失败");
            return "";
        }
    }
}
